/**
 * 在线考试
 */
<template>
    <div class="drawer">
        <el-drawer
            v-model="open"
            size="100%"
            direction="ttb"
            :destroy-on-close="true"
            :before-close="handleBeforeClose"
        >
            <template #header>
                <vp-label zh="考试" en="Exam" />
            </template>
            <el-row v-loading="loading" :gutter="12" class="m10">
                <el-col :span="8">
                    <vp-card style="min-height: calc(100vh - 80px);">
                        <template #header>
                            <vp-label zh="答题卡" en="Answer Sheet" />
                        </template>
                        <el-countdown 
                            title="距离考试结束" 
                            :value="getCountdown()" 
                            @finish="handleFinish" 
                            style="text-align: center;padding-bottom: 10px;"
                        />
                        <el-row style="padding: 20px 28px 0px 28px;">
                            <el-col :span="24" class="pb15">
                                <vp-label zh="考生姓名" en="Name" style="width: 70px;" />
                                <span style="color:var(--van-gray-7);padding-left: 5px;">{{ exam.person?.ryxm }}</span>
                            </el-col>
                            <el-col :span="24" class="pb15">
                                <vp-label zh="考试科目" en="Subject" style="width: 70px;" />
                                <span style="color:var(--van-gray-7);padding-left: 5px;">{{ exam.plan?.kcmcZw }}</span>
                            </el-col>
                            <el-col :span="24" class="pb15">
                                <vp-label zh="考试时长" en="Duration" style="width: 70px;" />
                                <span style="color:var(--van-gray-7);padding-left: 5px;">{{ exam.zgsc }}分钟</span>
                            </el-col>
                            <el-col :span="24">
                                <vp-label zh="总分" en="Total Score" style="width: 70px;" />
                                <span style="color:var(--van-gray-7);padding-left: 5px;">{{ exam.zf }}分</span>
                            </el-col>
                        </el-row>
                        <el-divider />
                        <div style="padding: 10px 28px 0 28px;">
                            <div>
                                <span class="color-info">题目面板示例</span>
                                <span class="color-danger">（点击题号可直接进入该考题）</span>
                            </div>
                        </div>
                        <el-row style="width: 100%;padding: 10px 28px 0 28px;" :gutter="20">
                            <el-col :span="12">
                                <div style="display: flex;align-items: center;">
                                    <el-button type="primary" style="width: 30px;border-radius: 2px;cursor: default;background-color: rgb(240, 240, 240);" class="numberBtnFinished"></el-button>
                                    <div style="padding-left: 8px;"><vp-label zh="已回答" en="Answered" /></div>
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <div style="display: flex;align-items: center;">
                                    <el-button type="default" style="width: 30px;border-radius: 2px;cursor: default;background-color: rgb(240, 240, 240);" class="numberBtnUnanswer"></el-button>
                                    <div style="padding-left: 8px;"><vp-label zh="未回答" en="Unanswered" /></div>
                                </div>
                            </el-col>
                        </el-row>
                        <el-divider border-style="dashed" style="margin: 12px 0 24px 0" />
                        <el-space wrap style="padding: 0 28px;">
                            <el-button 
                                v-for="item in (exam.examQuestions || [])"
                                :key="item.id"
                                style="width: 30px;border-radius: 2px;background-color: rgb(240, 240, 240);"
                                :class="(item.dtbs === 1 ? 'numberBtnFinished' : 'numberBtnUnanswer') + ' ' + (question.id === item.id ? 'numberBtnSelected' : '')"
                                @click="handleChangeQuestion(item.xh)"
                            >
                                {{item.xh}}
                            </el-button >
                        </el-space>
                    </vp-card>
                </el-col>
                <el-col :span="16">
                    <vp-card style="min-height: calc(100vh - 80px);">
                        <template #header>
                            <vp-label zh="题目" en="Question" />
                        </template>
                        <van-cell-group style="margin-top: 4px;margin-top: 4px;height: calc(100vh - 185px);overflow-y: auto;">
                            <div style="padding: 12px;">
                                <div>
                                    <span style="font-weight: bold;" v-if="question.id">
                                        {{ question.xh + '.' }}
                                        [{{ question.tmlx === 10 ? '单选' : 
                                            question.tmlx === 15 ? '单选' : 
                                            question.tmlx === 30 ? '多选' : '未知' }}]
                                    </span>
                                    <span style="padding-left: 8px;">{{ questionStem.ms }}</span>
                                    <span style="padding-left: 8px;" class="color-info">{{ "(" + question.btfs + "分)"}}</span>
                                </div>
                                <div v-if="questionStem.images">
                                    <el-image
                                        v-for="image in questionStem.images"
                                        :key="image.id"
                                        :src='`${baseURL}/file/stream/${image.id}`'
                                    />
                                </div>
                                <div v-if="questionStem.videos">
                                    <div
                                        v-for="media in questionStem.videos"
                                        :key="media.id"
                                    >
                                        <video 
                                            v-if="['MP3', 'MP4', 'M3U8'].includes(media.hzm)"
                                            :src="`${baseURL}/file/stream/${media.id}`"
                                            style="width: 100%;" 
                                            ref="vedioRef" 
                                            controls 
                                        >
                                        </video>
                                    </div>
                                </div>
                                <el-checkbox-group v-model="question.checkedAnswer" class="pt20">
                                    <el-checkbox 
                                        v-for="choice in questionChoices"
                                        :key="choice.id"
                                        :value="choice.xh"
                                        style="padding: 16px 0;"
                                        size="large"
                                        @change="handleClickAnswer(choice)"
                                        class="w100"
                                    >
                                        <div>
                                            <span>{{ String.fromCharCode(choice.xh+65) + '.'}}</span>
                                            <span>{{ choice.ms }}</span>
                                        </div>
                                    </el-checkbox>
                                </el-checkbox-group>
                            </div>
                        </van-cell-group>

                        <el-space style="width: 100%;" :gutter="20">
                            <el-button v-if="question.xh > 1" @click="handleChangeQuestion(question.xh-1)">
                                <vp-label zh="上一题" en="Last Question" />
                            </el-button>
                            <el-button v-if="question.xh < exam.examQuestions?.length" @click="handleChangeQuestion(question.xh+1)">
                                <vp-label zh="下一题" en="Next Question" />
                            </el-button>
                            <el-button type="danger"block v-else @click="handleConfirmSubmit">
                                <vp-label zh="提交试卷" en="Submit Exam" />
                            </el-button>
                        </el-space>
                    </vp-card>
                </el-col>
            </el-row>
        </el-drawer>
    </div>
</template>
<script setup lang="ts" name="vpOnlineExam">
import { computed, ref } from 'vue';
import { parseISO, differenceInMinutes } from 'date-fns';
import request from '/@/utils/request';
import { ElMessage } from 'element-plus';
import VpMessageBox from '/@/components/vp/VpMessageBox';
  
const loading = ref(false);
const baseURL = import.meta.env.VITE_API_URL as any;
const open = ref(false);
const emits = defineEmits(['close']);
const id = ref('');

const exam = ref<any>({});
const question = ref<any>({});

// 打卡页面
const handleOpen=(param: any)=>{
    loading.value = true;
    id.value = param.id;
    open.value = true;
    // 开始考试
    handleStartExam();
}

// 开始考试
const handleStartExam = () => {
    request.post(`/training/exam/start/${id.value}`).then((res: any)=>{
        exam.value = {
            ...res.data,
            examQuestions: (res.data.examQuestions || []).map((obj: any, i:number) => {
                return {
                    ...obj,
                    xh: i + 1,
                    checkedAnswer: convert2CheckedAnswer(obj.dt),
                }
            })
        }
        question.value = exam.value.examQuestions[0];
    }).catch(() => {
        setTimeout(() => {
            handleClose();
        }, 2000)
    }).finally(() => {
        loading.value = false;
    });
}

// 将答题描述转换,比如1011 -> [0,2,3]
const convert2CheckedAnswer = (dt: string) => {
    let selected = [] as number[];
    if(dt){
        dt.split("").map((item, index)=>{
            if(item === "1"){
                selected.push(index);
            }
        });
    }
    return selected;
}

// 倒计时
const getCountdown = () => {
    if (!exam.value.kssj) {
        return Date.now() + 7200000;
    }
    const startTime = parseISO(exam.value?.kssj).getTime();
    const endTime = startTime + 1000 * 60 * (exam.value.zgsc || 120);
    return endTime;
}

// 获取题干
const questionStem = computed(() => {
    if(!question.value.examQuestionAnswers || question.value.examQuestionAnswers.length === 0){
        return {};
    }
    const filterList = question.value.examQuestionAnswers.filter((item:any)=> item.mxlx===10);
    if(!filterList || filterList.length == 0){
        return {};
    }
    return filterList[0];
});

// 获取选项
const questionChoices = computed(() => {
    if(!question.value.examQuestionAnswers || question.value.examQuestionAnswers.length === 0){
        return [];
    }
    return question.value.examQuestionAnswers.filter((item:any)=> item.mxlx===20).map((item:any, index: number) => {
        return {
            ...item,
            xh: index,
        }
    });
});

// 选项改变
const handleClickAnswer = (choice: any) => {
    if (question.value.tmlx !== 30) {
        question.value.checkedAnswer = [choice.xh];
    }
    question.value.dt = question.value.examQuestionAnswers.filter((item:any)=> item.mxlx===20).map((item:any, index:number)=>{
        return question.value.checkedAnswer.indexOf(index) >= 0 ? 1 : 0;
    }).join("");
    question.value.dtbs = question.value.checkedAnswer.length > 0 ? 1 : 0;

    request.post('/training/exam/answer/save', {
        id: question.value.id,
        mainid: id.value,
        dt: question.value.dt,
        dtbs: question.value.dtbs
    }).catch(() => {
        setTimeout(() => {
            handleClose();
        }, 2000)
    });
}

// 切换当前题目
const handleChangeQuestion = (newIndex: number) => {
    if (newIndex >= 0 && newIndex <= exam.value.examQuestions.length) {
        question.value = exam.value.examQuestions[newIndex - 1];
    }
}

// 学员提交试卷
const handleConfirmSubmit = () => {
    const kssc = differenceInMinutes(new Date(), parseISO(exam.value?.kssj));
    if (exam.value.zdsc && kssc < exam.value.zdsc) {
        ElMessage.error(`最低考试时长为${exam.value.zdsc}分钟，无法交卷！`);
    } else {
        VpMessageBox.confirm({
            zh: '你确定要提交试卷吗？',
            en: 'Are you sure you want to submit this exam paper?',
        }, {
            zh: '提交试卷',
            en: 'Submit Exam',
        }, {
            type: 'warning',
        }).then(() => {
            handleSubmit();
        }).catch(() => {
        });
    }
}

// 考试结束，自动交卷
const handleFinish = () => {
    ElMessage.error("考试已结束，试卷已自动提交 Exam Has Ended, and the Exam Paper Has Been Automatically Submitted");
    handleSubmit();
}

// 保存试卷
const handleSubmit = () => {
    loading.value = true;
    request.post(`/training/exam/submit/${id.value}`).then(()=>{
        loading.value = false;
        handleClose();
    });
}

// 关闭前的回调
const handleBeforeClose = (done: () => void)=>{
    done();
    emits("close");
}

// 关闭页面
const handleClose = () => {
    open.value = false;
    emits("close");
}

defineExpose({
    handleOpen,
})

</script>
<style scoped lang="scss">
    .colon {
        display: inline-block;
        margin: 0 4px;
        color: #1989fa;
    }
    .block {
        display: inline-block;
        width: 22px;
        color: #fff;
        font-size: 12px;
        text-align: center;
        background-color: #1989fa;
    }

    .numberBtnFinished{
        background-color: #389e0d !important;
        color: #fff;
    }

    .numberBtnUnsure{
        background-color: #FAAC58 !important;
        color: #fff;
    }

    .numberBtnSelected{
        border: black 2px solid;
    }

    :deep(.el-image__inner) {
        object-fit: contain;
        max-width: 800px;
        max-height: 400px;
    }
</style>